<template>
  <div class="user-center-container">
    <a-card class="user-center-card" :loading="loading">
      <!-- 头部用户信息 -->
      <div class="user-header">
        <div class="avatar-section">
          <a-avatar 
            :size="120" 
            :src="formData.userAvatar"
            class="user-avatar"
          >
            <template #icon>
              <UserOutlined />
            </template>
          </a-avatar>
          <a-button 
            type="link" 
            @click="showAvatarModal = true"
            class="change-avatar-btn"
          >
            更换头像
          </a-button>
        </div>
        <div class="user-info-section">
          <h2 class="user-name">{{ userInfo?.userName || '未设置昵称' }}</h2>
          <p class="user-account">账号：{{ userInfo?.userAccount }}</p>
          <p class="user-role">
            <a-tag :color="getRoleColor(userInfo?.userRole)">
              {{ getRoleText(userInfo?.userRole) }}
            </a-tag>
          </p>
          <div class="user-time-info">
            <p class="join-time">
              <CalendarOutlined />
              注册时间：{{ formatTime(userInfo?.createTime) }}
            </p>
            <p class="last-update">
              <ClockCircleOutlined />
              最后更新：{{ formatTime(userInfo?.updateTime) }}
            </p>
          </div>
        </div>
      </div>

      <a-divider />

      <!-- 用户信息编辑表单 -->
      <div class="user-form-section">
        <h3 class="section-title">个人信息</h3>
        <a-form
          :model="formData"
          :rules="formRules"
          layout="vertical"
          @finish="handleUpdate"
          class="user-form"
        >
          <a-form-item label="用户昵称" name="userName">
            <a-input
              v-model:value="formData.userName"
              placeholder="请输入用户昵称"
              :prefix="h(UserOutlined)"
              size="large"
            />
          </a-form-item>

          <a-form-item label="个人简介" name="userProfile">
            <a-textarea
              v-model:value="formData.userProfile"
              placeholder="请输入个人简介"
              :rows="4"
              :max-length="200"
              show-count
            />
          </a-form-item>

          <div class="form-actions">
            <a-button type="primary" html-type="submit" size="large" :loading="updating">
              <SaveOutlined />
              保存修改
            </a-button>
            <a-button @click="resetForm" size="large">
              <ReloadOutlined />
              重置
            </a-button>
          </div>
        </a-form>
      </div>
    </a-card>

    <!-- 更换头像弹窗 -->
    <a-modal
      v-model:open="showAvatarModal"
      title="更换头像"
      @ok="handleAvatarChange"
      @cancel="showAvatarModal = false"
      :confirm-loading="uploading"
    >
      <div class="avatar-modal-content">
        <div class="current-avatar">
          <p>当前头像：</p>
          <a-avatar :size="80" :src="formData.userAvatar">
            <template #icon>
              <UserOutlined />
            </template>
          </a-avatar>
        </div>
        
        <a-divider />
        
        <div class="new-avatar">
          <p>新头像链接：</p>
          <a-input
            v-model:value="newAvatarUrl"
            placeholder="请输入新头像链接"
            size="large"
          />
          <div class="avatar-preview" v-if="newAvatarUrl">
            <p>预览：</p>
            <a-avatar :size="80" :src="newAvatarUrl">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, h } from 'vue'
import { 
  UserOutlined, 
  SaveOutlined, 
  ReloadOutlined,
  CalendarOutlined,
  ClockCircleOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getLoginUser, updateUser } from '@/api/userController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import dayjs from 'dayjs'

// 状态管理
const loginUserStore = useLoginUserStore()
const loading = ref(false)
const updating = ref(false)
const uploading = ref(false)
const showAvatarModal = ref(false)
const newAvatarUrl = ref('')

// 用户信息
const userInfo = ref<API.UserVO>()
const formData = ref<API.UserUpdateRequest>({
  userName: '',
  userAvatar: '',
  userProfile: '',
})

// 表单验证规则
const formRules = {
  userName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度应在2-20个字符之间', trigger: 'blur' }
  ],
  userProfile: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  try {
    const res = await getLoginUser()
    if (res.data.code === 0 && res.data.data) {
      userInfo.value = res.data.data
      // 初始化表单数据
      formData.value = {
        id: res.data.data.id,
        userName: res.data.data.userName || '',
        userAvatar: res.data.data.userAvatar || '',
        userProfile: res.data.data.userProfile || '',
      }
    } else {
      message.error('获取用户信息失败：' + res.data.message)
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    message.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 更新用户信息
const handleUpdate = async () => {
  updating.value = true
  try {
    const res = await updateUser(formData.value)
    if (res.data.code === 0) {
      message.success('更新成功')
      // 刷新用户信息
      await fetchUserInfo()
      // 更新全局用户状态
      await loginUserStore.fetchLoginUser()
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    console.error('更新用户信息失败：', error)
    message.error('更新失败')
  } finally {
    updating.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (userInfo.value) {
    formData.value = {
      id: userInfo.value.id,
      userName: userInfo.value.userName || '',
      userAvatar: userInfo.value.userAvatar || '',
      userProfile: userInfo.value.userProfile || '',
    }
  }
}

// 处理头像更换
const handleAvatarChange = () => {
  if (newAvatarUrl.value) {
    formData.value.userAvatar = newAvatarUrl.value
    showAvatarModal.value = false
    newAvatarUrl.value = ''
    message.success('头像已更新，请点击保存修改')
  } else {
    message.warning('请输入有效的头像链接')
  }
}

// 获取角色颜色
const getRoleColor = (role?: string) => {
  const roleColors: Record<string, string> = {
    'admin': 'red',
    'user': 'blue',
    'vip': 'gold'
  }
  return roleColors[role || 'user'] || 'default'
}

// 获取角色文本
const getRoleText = (role?: string) => {
  const roleTexts: Record<string, string> = {
    'admin': '管理员',
    'user': '普通用户',
    'vip': 'VIP用户'
  }
  return roleTexts[role || 'user'] || '未知角色'
}

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return '未知'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 页面初始化
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.user-center-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.user-center-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-header {
  display: flex;
  gap: 32px;
  align-items: flex-start;
  margin-bottom: 24px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  border: 4px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.change-avatar-btn {
  font-size: 12px;
  color: #1890ff;
}

.user-info-section {
  flex: 1;
}

.user-name {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #262626;
}

.user-account {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #8c8c8c;
}

.user-role {
  margin: 0 0 16px 0;
}

.user-time-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.join-time, .last-update {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #8c8c8c;
}

.section-title {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.user-form {
  max-width: 800px;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.avatar-modal-content {
  padding: 16px 0;
}

.current-avatar,
.new-avatar {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.avatar-preview {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.avatar-preview p {
  margin: 0;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-center-container {
    padding: 16px;
  }
  
  .user-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .user-info-section {
    width: 100%;
  }
  
  .form-actions {
    justify-content: center;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .user-center-card {
    background: #1f1f1f;
    border-color: #303030;
  }
  
  .user-name {
    color: #ffffff;
  }
  
  .section-title {
    color: #ffffff;
  }
}
</style>
